/**
 * @param {number[][]} grid1
 * @param {number[][]} grid2
 * @return {number}
 */
 var countSubIslands = function(grid1, grid2) {
    const m = grid1.length, n = grid1[0].length
    const dfs = (i, j) => {
        if(i < 0 || i >=m || j < 0 || j >= n || grid2[i][j] === 0){
            return true
        }
        if(grid1[i][j] === 0 && grid2[i][j] === 1){
            return false
        }
        grid2[i][j] = 0
        let flag = dfs(i, j+1) &&
        dfs(i+1, j) &&
        dfs(i-1, j) &&
        dfs(i, j-1)
        if(!flag){
            grid2[i][j] = 1
            return false
        }
        return true
    }
    let ans = 0
    for(let i = 0; i<m; i++){
        for(let j = 0; j<n; j++){
            if(grid1[i][j] === 1 && grid2[i][j] === 1){
                if(dfs(i, j)){
                    ans++
                }
                
            }
        }
    } 
    
    return ans
};